use std::collections::HashMap;

use serde::{Deserialize, Serialize};
#[cfg(feature = "ssr")]
use crate::base::{Error, Result};
use crate::structs::{FieldProps, ImportMode};
#[derive(Debug, PartialEq, Eq, Clone, Serialize, Deserialize)]
pub struct ImportProps {
    /** 导入模版的名称 */
    #[serde(default)]
    pub template_name: Option<String>,
    /** 导入方式 */
    pub import_mode: ImportMode,
    /** 导入时区分一条数据的唯一键，用于导入模式InsertAndUpdate*/
    #[serde(default)]
    pub unique_keys: Vec<String>,
    /** 导入使用的参数，填写column的name,用于导入模式DeleteAfterInsert，按照此参数的值先删除*/
    #[serde(default)]
    pub param_names: Vec<String>,
    /** 字段映射 */
    pub col_map: HashMap<String, String>,
    /** 开始行号 */
    #[serde(default = "start_row_default")]
    pub start_row: usize,
    /** 指定的列为空则跳过 */
    #[serde(default)]
    pub skip_empty_cols: Vec<String>,
}
fn start_row_default() -> usize {
    2
}
#[cfg(feature = "ssr")]
impl ImportProps {
    pub fn parse(&self, dao_name: &str, fps: &Vec<FieldProps>) -> Result<()> {
        if ImportMode::InsertAndUpdate == self.import_mode {
            if self.unique_keys.is_empty() {
                return Err(Error::Conf(
                    "导入方式为InsertAndUpdate,unique_keys不能为空".to_string(),
                ));
            } else {
                for k in &self.unique_keys {
                    if !fps.iter().any(|f| f.name.as_str() == k) {
                        return Err(Error::Conf(format!(
                            "import_props-unique_keys配置字段值{}在实体类{}中不存在",
                            k, dao_name
                        )));
                    }
                }
            }
        } else if ImportMode::DeleteAfterInsert == self.import_mode {
            if self.param_names.is_empty() {
                return Err(Error::Conf(
                    "导入方式为DeleteAfterInsert,param_names不能为空".to_string(),
                ));
            }
        }
        for name in &self.param_names {
            if !fps.iter().any(|f| f.name.as_str() == name) {
                return Err(Error::Conf(format!(
                    "import_props-param_names配置字段值{}在实体类{}中不存在",
                    name, dao_name
                )));
            }
        }
        for (k, v) in &self.col_map {
            if !fps.iter().any(|f| f.name.as_str() == k) {
                return Err(Error::Conf(format!(
                    "import_props-col_map配置字段值{}在实体类{}中不存在",
                    k, dao_name
                )));
            }
            for &c in v.as_bytes().iter() {
                if !c.is_ascii_uppercase(){
                    return Err(Error::Conf(format!(
                        "import_props-col_map配置excel列名{}必须为大写字母",
                        v
                    )));
                }
            }
        }
        Ok(())
    }
}